package cn.rengy.tpa.wxmp.material;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;

import com.alibaba.fastjson.JSONObject;

import cn.rengy.tool.http.HttpUtils;
import cn.rengy.tpa.wxmp.exception.WeChatException;
import cn.rengy.tpa.wxmp.token.AccessToken;
import cn.rengy.tpa.wxmp.util.WeChatReturnCode;
import cn.rengy.tpa.wxmp.util.WeChatUtil;

/**
 *   临时素材接口
 *  <a href="https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738730">文档地址</a>
 * @author rengy
 * 
 */
public class TempMediaApi {
	
	private static Logger logger = LoggerFactory.getLogger(TempMediaApi.class);
	private static final MediaType MEDIA_TYPE_IMAGE=MediaType.valueOf("image/*");
	private static final String UPLOAD="http://api.weixin.qq.com/cgi-bin/media/upload?type=";
	private static final String GETURL="http://api.weixin.qq.com/cgi-bin/media/get?media_id=";
	private static final String PARAM_FILE = "media";
	
	public static File get(AccessToken accessToken,String media_id,File targetDirectory) throws ClientProtocolException, IOException {
		String url=new StringBuilder(GETURL).append(media_id).append("&access_token=").toString();
		for(int i=0;i<2;i++) {
			Request request = Request.Get(url+accessToken.token());
			HttpResponse httpResponse = request.execute().returnResponse();
			HttpEntity httpEntity=httpResponse.getEntity();
			String contentType=httpEntity.getContentType().getValue();
			MediaType mediaType=MediaType.valueOf(contentType);
			if(MediaType.APPLICATION_JSON.isCompatibleWith(mediaType)||MediaType.TEXT_PLAIN.isCompatibleWith(mediaType)) {
				String jsonString=EntityUtils.toString(httpEntity,Consts.UTF_8);
				JSONObject resultObject=JSONObject.parseObject(jsonString);
				int errCode =resultObject.getIntValue("errcode");
				if(errCode==0){
					String video_url=resultObject.getString("video_url");
					return null;
				}else if(WeChatUtil.isAccessTokenInvalid(errCode)){
					accessToken.refresh();
				}else{
					String errMsg = WeChatReturnCode.getMsg(errCode,resultObject.getString("errmsg"));
					throw new WeChatException(errCode,errMsg);
				}
			}else if(MEDIA_TYPE_IMAGE.includes(mediaType)){
				String newFileName=null;
				Header header=httpResponse.getFirstHeader("Content-disposition");
				if(header!=null){
					HeaderElement headerElement=header.getElements()[0];
					String fileName=headerElement.getParameterByName("filename").getValue();
					newFileName=UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(fileName);
				}else {
					//解析后缀
					throw new WeChatException("Content-disposition为空");
				}
				File targetFile = new File(targetDirectory ,newFileName);
				FileCopyUtils.copy(httpEntity.getContent(), new FileOutputStream(targetFile));
				return targetFile;
			}else {
				logger.info(url);
				logger.error(mediaType.toString());
			}
		}
		return null;
	}
	/**
	 * 上传临时素材
	 * 图片（image）: 2M，支持PNG\JPEG\JPG\GIF格式
	 语音（voice）：2M，播放长度不超过60s，支持AMR\MP3格式
	 视频（video）：10MB，支持MP4格式
	 缩略图（thumb）：64KB，支持JPG格式
	 * @return
	 */
	public static String upload(AccessToken accessToken,File file,MaterialType type) {
		//long length=file.length();
		//校验长度
		//TYPEACCESS_TOKEN
		String url=new StringBuilder(UPLOAD).append(type.name()).append("&access_token=").toString();
		int j=3;
		int i=2;
		int max=i+j;
		for(;(i>0||j>0)&&max>0;max--){
			String result = HttpUtils.postFile(url+accessToken.token(),PARAM_FILE, file);
			JSONObject resultObject = JSONObject.parseObject(result);
			int errCode =resultObject.getIntValue("errcode");
			if(errCode==0) {
				return resultObject.getString("media_id");
			}else if(errCode==-1) {
				j--;
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
				}
			}else if(WeChatUtil.isAccessTokenInvalid(errCode)) {
				i--;
				accessToken.refresh();
			}else {
				String errMsg = WeChatReturnCode.getMsg(errCode,resultObject.getString("errmsg"));
				throw new WeChatException(errCode,errMsg);
			}
		}
		throw new WeChatException("上传失败");
	}
	
}
